//
//  BleDataTool.swift
//  XLProject
//
//  Created by xinglian on 2022/12/8.
//

import UIKit
import Foundation
import CoreBluetooth

enum BleDataConfig : String{
    ///厂商字段
    case productName = "c003"
    ///数据服务
    case service = "1F40EAF8-AAB4-14A3-F1BA-F61F35CDDBAA"
    ///指令发送通道
    case writeChannel = "1F400001-AAB4-14A3-F1BA-F61F35CDDBAA"
    ///实时数据传输通道
    case readChannel = "1F400002-AAB4-14A3-F1BA-F61F35CDDBAA"
    ///传图片的通道
    case writeChannel03 = "1F400003-AAB4-14A3-F1BA-F61F35CDDBAA"
    ///OTA 指令发送通道
    case writeChannelOTA = "02F00000-0000-0000-0000-00000000FF01"
    ///OTA 数据返回通道
    case readChannelOTA = "02F00000-0000-0000-0000-00000000FF02"
    ///OTA服务
    case serviceOTA = "02F00000-0000-0000-0000-00000000FE00"
}
///3.11.4，设备返回回调
public let BLE3114Response = NSNotification.Name("BLE3114Response")
///3.10.4，擦除FLASH回调
public let BLE3104Response = NSNotification.Name("BLE3104Response")
///3.10.6，设备同步更新flash数据包的状态
public let BLE3106Response = NSNotification.Name("BLE3106Response")
///3.2.2，固件信息
public let BLE322Response = NSNotification.Name("BLE322Response")
///3.6.10，固件信息
public let BLE3610Response = NSNotification.Name("BLE3610Response")
///3.2.21 APP 端获取定制案参数接口-记事本概要信息
public let BLE3221Response = NSNotification.Name("BLE3221Response")
///OTA 读取首地址
public let BLEFirstAddressResponse = NSNotification.Name("BLEFirstAddressResponse")
///OTA 擦除地址
public let BLEClearAddressResponse = NSNotification.Name("BLEClearAddressResponse")
///OTA 写入数据
public let BLEWriteAddressResponse = NSNotification.Name("BLEWriteAddressResponse")
class BleDataTool: NSObject {
    static let share = BleDataTool()
    private override init() {}
    private var writeChar01 : CBCharacteristic?
    private var writeChar03 : CBCharacteristic?
    private var readChar : CBCharacteristic?
    private var writeOTA : CBCharacteristic?
    private var readOTA : CBCharacteristic?
    private var currentChar : CBCharacteristic?
    private var currentData : Data?
    var periphral : CBPeripheral?
    
    ///检查键盘开机状态
    func check(){
        guard let writechar = self.writeChar01 else{return}
        write("8800000000000300001300".hexadecimal()!, writechar, .withResponse)
    }
    
    /// 命令走完，把这两个参数置空
    func setnil(){
        self.currentChar = nil
        self.currentData = nil
    }
    
    ///app设置设备恢复出厂设置
    func reset(){
        let str = "8800000000000300010100".hexadecimal()!
        write(str, writeChar01!, .withResponse)
    }
    /// 键盘控制命令
    /// - Parameter hex:
    ///    00 = 保留
    ///    01 = 开始运行开机logo
    ///    02 = 运行状态
    ///    03 = 图片传输中
    ///    04 = 息屏待机阶段
    func setupKeyboard(_ hex:String){
        let str = "8800000000000600011C010001" + hex
        write(str.hexadecimal()!, writeChar01!, .withResponse)
    }
    
    ///默认动画
    func defultLogo(){
        self.currentChar = self.writeChar01
        self.currentData = "880000000000060009070000FFFE".hexadecimal()
        self.check()
    }
    
    ///3.2.1获取固件信息
    func firmwareVersion(){
        let str = "8800000000000200" + "0001"
        self.currentChar = self.writeChar01
        self.currentData = str.hexadecimal()
        self.check()
    }
    ///3.6.1设置时间
    func setDate(){
        self.currentChar = self.writeChar01
        let stamp = NSDate.currentTimeStamp("yyyy/MM/dd/HH/mm/ss")
        let turple = KBTool.dateHex(Int(stamp)!)
        let s = "8800000000000900"+"0401"+turple.date
        self.currentData = s.hexadecimal()
        self.check()
    }
    ///3.6.2 APP端设置设备基本信息
    func setupConfig(){
        self.currentChar = self.writeChar01
        let sex = "00"
        let age = "00"
        let h = "00"
        let w = "00"
        let language = APP.language == "zh" ? "00" : "01"
        let time = "00"
        let unit = "00"
        let version = "00"
        let hands = "00"
        let t = "00"
        let step = "00000000"
        let s = "8800000000001000"+"0402"+sex+age+h+w+language+time+unit+version+hands+t+step
        self.currentData = s.hexadecimal()
        self.check()
    }
    
    ///3.2.21 APP 端获取定制案参数接口-记事本概要信息
    func getNoteInfo(){
        self.currentChar = self.writeChar01
        self.currentData = "8800000000000300001500".hexadecimal()
        self.check()
    }
    
    ///3.6.10 传记事本到设备
    func upload(_ stamp:Int=0,_ str:String,_ isTitle:Bool){
        let turple = KBTool.dateHex(stamp)
        
        ///标题转utf16的unicode
        var utf_title = ""
        let utf16_title = str.utf16
        let max_length = isTitle ? 80 : 200 ///是标题的话，最大80字节，内容最大200字节
        for s in utf16_title{
            ///汉字的unicode有4位，英文的unicode是2位，不足4位，前面补0
            utf_title += "\(s)".toHex().fix(4, "0") as String
            if utf_title.count / 2 >= max_length {///每次传输不能超过最大限制的字节
                break
            }
        }
        ///标题长度
        let title_lenght = "\(utf_title.count / 2)".toHex().fix(4, "0") as String
        
        ///command+key+索引 01+日期字节长度+日期+索引02+标题字节长度+加标题
        let tag = isTitle ? "02" : "03"///标题的索引，和内容的索引
        let datestr = isTitle ? "01"+"0008"+turple.date+turple.week : ""///标题加日期，内容不加日期，直接发
        let dataStr = "040A"+datestr+"\(tag)"+title_lenght+utf_title
        
        self.currentChar = self.writeChar01
        self.currentData = self.header(dataStr).hexadecimal()
        self.check()
    }
    
    /// ///3.6.11 删除记事本
    func delete(_ stamp:String){
        self.currentChar = self.writeChar01
        let stampstr = stamp.toHex().fix(8, "0") as String
        self.currentData = ("8800000000000600040B"+stampstr).hexadecimal()
        self.check()
    }
    
    ///传多张图（gif）
    func setGIF(_ array:[Data], _ speed:Int?=6, block:@escaping(_ data:NSData)->Void){
        guard let p = periphral, p.state == .connected else{
            CCHud.start(LS("请先连接设备"), stopTime: Int32(1.5))
            return
        }
        DispatchQueue.main.async {
            ///如果是单张图片
            if array.count == 1 {
                let data = array[0] as NSData
                BleDataTool.share.setImgInfo(false,"\(data.count)")
                block(data)
            }
            
            ///如果是多张图片
            var a = KBTool.binToString("A")
            var b = KBTool.binToString("B")
            var c = "00000000"
            var d = ""
            let e = "FCFF0000"
            
            
            ///a
            /// 几张图，替换到相应位置
            let count = "\(array.count)".toHex().fix(4, "0") as String
            a.replace(r: 24...27, content:KBTool.reverse(count))
            
            ///b
            /// 设置指定动画时间
            /// 几张图
            let time = "\(speed!)".toHex().fix(2, "0") as String
            let countB = "\(array.count)".toHex().fix(2, "0") as String
            b.replace(r: 64...65, content:KBTool.reverse(time))
            b.replace(r: 70...71, content:KBTool.reverse(countB))
            
            ///c
            var count_temp = 0
            for i in 0..<array.count{
                if i < array.count - 1{
                    let data = array[i]
                    count_temp += data.count
                    let count = "\(count_temp)".toHex().fix(8, "0") as String
                    c += KBTool.reverse(count)
                }
            }
            
            
            ///d
            for data in array{
                d += KBTool.dataToString(data)
            }
            
            ///这里+16因为，A后面接4个4bytes的abcd，固定的16个bytes。
            let lenght_a = "\(a.count / 2 + 16)".toHex().fix(8, "0") as String
            let lenght_b = "\((a.count + b.count) / 2 + 16)".toHex().fix(8, "0") as String
            let lenght_c = "\((a.count + b.count + c.count) / 2 + 16)".toHex().fix(8, "0") as String
            let lenght_d = "\((a.count + b.count + c.count + d.count) / 2 + 16)".toHex().fix(8, "0") as String
            a.append(KBTool.reverse(lenght_a))
            a.append(KBTool.reverse(lenght_b))
            a.append(KBTool.reverse(lenght_c))
            a.append(KBTool.reverse(lenght_d))
            
            let result =  a+b+c+d+e
            let size = result.count / 2
            BleDataTool.share.setImgInfo(true,"\(size)")
            block(result.hexadecimal()! as NSData)
        }
    }
    ///3.11.3 flash概要信息
    func setImgInfo(_ isBin:Bool,_ sizestr:String?=nil){
        var dataStr = ""
        if isBin == false{
            let ui = "FFFD".fixString(8, "0") as String
            let size = "0".toHex().fix(8, "0") as String
            ///command+key+索引 01+索引后面数据的字节长度+UI特征编号+表盘大小+颜色+内容+位置
            dataStr = "0903"+"01"+"000B"+ui+size+"00"+"00"+"00"
        }else{
            let size = sizestr!.toHex().fix(8, "0") as String
            dataStr = "0903"+"04"+"0008"+"0000FFFC"+size+"05"+"0000"
        }
        self.currentChar = self.writeChar01
        self.currentData = self.header(dataStr).hexadecimal()
        self.check()
    }
    
    ///3.10.3协议 擦除制定flash区域
    func clearFlash(){
        ///command+key++起始位置+结束位置
        ///自定义表盘和市场表盘开始和结束都是 0x00FFFFFF   16777215
        let dataStr = "0803"+"00FFFFFF"+"00FFFFFF"
        write(header(dataStr).hexadecimal()!, writeChar01!, .withoutResponse)
    }
    ///3.10.5 APP传输flash数据给设备
    func sendImgData(_ array:[Any], _ index:Int){
        if array.count <= 0 || index >= array.count {return}
        let subArray = array[index] as! Array<NSMutableData>
        for data in subArray
        {
            write(data as Data, writeChar03!, .withoutResponse)
            
        }
    }
    
    
    //MARK: - OTA  -------------------------------start----------------------------------------
    ///步骤2，手机 APP 获取设备当前升级程序的存储起始地址
    func readStorageAddress(){
        let datastr = "01"+"0400"+"00000000"
        write(datastr.hexadecimal()!, writeOTA!, .withResponse)
    }
    ///步骤3，APP 发命令让设备擦除升级所需要的地址空间
    func clearStorageAddress(_ address:Int){
        let add_str = KBTool.reverse("\(address)".toHex().fix(8, "0") as String)
        let datastr = "03"+"0400"+add_str
        write(datastr.hexadecimal()!, writeOTA!, .withResponse)
    }
    ///步骤4，传升级数据，App 发送指令至设备
    func updateOTA(_ address:Int, _ bytes:[UInt8]){
        let add_str = KBTool.reverse("\(address)".toHex().fix(8, "0") as String)
        let head_str = "05"+"4102"+add_str+"EB00"
        let data_str = bytes.map {String(format: "%02X", $0)}.joined()
        let data = head_str + data_str
        write(data.hexadecimal()!, writeOTA!, .withoutResponse)
    }
    
    ///步骤5升级结束，重启 App 发送指令至设备，命令 0x09
    func resetOTA(_ length:Int,_ crc:Int){
        let length_str = KBTool.reverse("\(length)".toHex().fix(8, "0") as String)
        var crc_str = String(format: "%0x", crc)
        crc_str = KBTool.reverse(crc_str.fix(8, "0") as String)
        //        let crc_str =  KBTool.reverse("\(crc)".toHex().fix(8, "0") as String)
        //        let data_str = "09"+"0800"+length_str+"af8f5691"
        let data_str = "09"+"0800"+length_str+crc_str
        print("  ==============重启。\(data_str)")
        write(data_str.hexadecimal()!, writeOTA!, .withResponse)
    }
    //MARK: - OTA  -------------------------------end----------------------------------------
    
    func write(_ data:Data?, _ char:CBCharacteristic?,_ type:CBCharacteristicWriteType){
        guard let p = periphral, p.state == .connected else{
            CCHud.start(LS("请先连接设备"), stopTime: Int32(1.5))
            return
        }
        p.writeValue(data!, for: char!, type: type)
    }
    ///公用方法，拼接头''
    func header(_ hex:String)->String{
        return String(format:"880000%@00%@", "\(hex.count / 2)".toHex().fix(8, "0"), hex)
    }
}
//MARK: - BleManagerDelegate
extension BleDataTool:CCBleManagerDelegate{
    func centralManagerDidUpdateState(_ central: CBCentralManager) {}
    
    
    func retrieveConnectedPeripherals(_ central: CBCentralManager, _ systemConnect: [CBPeripheral]) -> [CBPeripheral] {
        var temp = [CBPeripheral]()
        ///1 获取本地数据库中，最后链接的外围设备
        let array = BLEDevice.bg_findAll(nil) as? [BLEDevice] ?? [BLEDevice]()
        ///2 从系统底层获取已连接的设备，并与本地数据库对比，找到相同的设备，进行mac，data赋值
        for m in systemConnect{
            //            if BleDataConfig.productName.rawValue != (m.name ?? "") {
            //                break
            //            }
            var connect = false
            for d in array{
                if d.id == m.identifier.uuidString{
                    m.mac = d.mac
                    m.advertData = d.data as NSData
                    connect = d.connect
                }
            }
            if connect{
                temp.insert(m, at: 0)
            }else{
                temp.append(m)
            }
        }
        return temp
    }
    
    
    func autoConnect(_ central: CBCentralManager, _ searchedPeripherals: [CBPeripheral]) -> [CBPeripheral] {
        return searchedPeripherals
    }
    
    func filter(_ central: CBCentralManager, _ peripheral: CBPeripheral, _ data: [String : Any], _ RSSI: NSNumber) -> Bool {
        print("===========\(peripheral.name) = \(peripheral.mac)")
        
        if peripheral.mac.count < 17{
            return false
        }
        let dict = data["kCBAdvDataManufacturerData"] as? NSData ?? NSData()
        let service = ((data["kCBAdvDataServiceUUIDs"] as? [CBUUID])?.first)?.uuidString as? String ?? ""
        let product = String(format: "%.2x%.2x", dict[0],dict[1])
        if BleDataConfig.productName.rawValue == product && BleDataConfig.service.rawValue == service{
            return true
        }
        return false
    }
    
    ///连接成功
    func conncted(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        self.periphral = peripheral
        peripheral.discoverServices(nil)///查找所有服务
        
        ///其他处理
        let model = BLEDevice.device(peripheral)
        model.connect = true
        let success = model.bg_saveOrUpdate()
        central.stopScan()
    }
    
    ///断开连接，更新本地数据库
    func disConnected(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        //        let model = BLEDevice.device(peripheral)
        //        let whereStr = "where \(bg_sqlKey("mac"))=\(bg_sqlValue("\(model.mac)"))"
        //        let success = BLEDevice.bg_delete(nil, where:whereStr)
        ///其他处理
        let model = BLEDevice.device(peripheral)
        model.connect = false
        let success = model.bg_saveOrUpdate()
        CCHud.start(LS("设备已断开连接"), stopTime: 2)
        //        self.currentVC().navigationController?.popToRootViewController(animated: true)
    }
    
}
//MARK: - BleManagerPeripheralDelegate
extension BleDataTool:CCBleManagerPeripheralDelegate{
    ///搜索到服务
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        for service in peripheral.services!{
            print("+++++++++++++++++ 服务 = \(service.uuid.uuidString)")
            //            if BleDataConfig.service.rawValue == service.uuid.uuidString{
            peripheral.discoverCharacteristics(nil, for: service)///查找特征值
            //            }
        }
    }
    ///搜索到特征
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if error != nil{
            print(" \n  >>>>>>>>>>>>>>>>>>>>>>>>>>111 搜索特征值失败： \(error?.localizedDescription ?? "")")
        }
        for char in service.characteristics!{
            peripheral.setNotifyValue(true, for: char)///订阅, 实时接
            print(">>>>>>>>>>>>>>>>>>>>>> 特征值: \(char.uuid.uuidString)")
            switch char.uuid.uuidString{
            case BleDataConfig.readChannel.rawValue:
                self.readChar = char
            case BleDataConfig.writeChannel.rawValue:
                self.writeChar01 = char
            case BleDataConfig.writeChannel03.rawValue:
                self.writeChar03 = char
            case BleDataConfig.writeChannelOTA.rawValue:
                self.writeOTA = char
            case BleDataConfig.readChannelOTA.rawValue:
                self.readOTA = char
            default:
                break
            }
        }
        self.setDate()///设置时间
        peripheral.maximumWriteValueLength(for: .withoutResponse)
        //peripheral.readValue(for: char)/// 接收一次(是读一次信息还是数据经常变实时接收视情况而定, 再决定使用哪个)
    }
    
    /// 设置通知的回调
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        if error != nil{
            return print(" \n  >>>>>>>>>>>>>>>>>>>>>>>>>> 通知的回调：= \(characteristic.uuid.uuidString) =  \(error?.localizedDescription ?? "")")
        }
        print("======= 通知 = \(characteristic.uuid.uuidString)")
    }
    ///写数据回调
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        
    }
    ///数据更新
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        let bytes = [UInt8](characteristic.value ?? Data())
        
        //MARK: - OTA  -------------------------------start----------------------------------------
        if characteristic.uuid.uuidString == self.readOTA?.uuid.uuidString{
            let opCode = String(format:"%.2x", bytes[1])
            switch opCode{
            case "01":///读取起始位置的回调
                if bytes[0] == 0x0{
                    let address = bytes[4...7].map{String(format:"%.2x", $0)}.joined()
                    NotificationCenter.default.post(name:BLEFirstAddressResponse, object:KBTool.reverse(address))
                }
            case "03":///擦除地址回调
                if bytes[0] == 0x0{
                    let address = bytes[4...7].map{String(format:"%.2x", $0)}.joined()
                    NotificationCenter.default.post(name:BLEClearAddressResponse, object:KBTool.reverse(address))
                }
            case "05":///写入数据回调
                if bytes[0] == 0x0{
                    let address = bytes[4...7].map{String(format:"%.2x", $0)}.joined()
                    let packet_len = bytes[8...9].map{String(format:"%.2x", $0)}.joined()
                    NotificationCenter.default.post(name:BLEWriteAddressResponse, object:["address":KBTool.reverse(address),"packet_len":KBTool.reverse(packet_len)])
                }
                else {
                    //                    let text = bytes[0...bytes.count].map{String(format:"%.2x", $0)}.joined()
                    //                    APP.logwindow.input.text =  "\(String(describing: APP.logwindow.input.text ?? "")) \n" + text
                    //                    APP.logwindow.input.scrollRangeToVisible(NSMakeRange(APP.logwindow.input.text.count, 0))
                }
            default:
                break
            }
            return
        }
        //MARK: - OTA  -------------------------------end----------------------------------------
        
        let heard = "数据头："+bytes[0...7].map{String(format:"%.2x", $0)}.joined()+" | "
        let payload = "数据长度: "+bytes[3...6].map{String(format:"%.2x", $0)}.joined()+" | "
        let command = String(format:"%.2x", bytes[8])
        let key = String(format:"%.2x", bytes[9])
        print("======= 数据回调 = \(characteristic.uuid.uuidString)"+heard+payload+"command: "+command+"  |  key:  "+key)
        let s = bytes[0...bytes.count - 1].map{String(format:"%.2x｜", $0)}.joined()
        print("======= 全部数据 = \(s)")
        switch (command,key){
        case ("00","14"):///查询是否开机
            let value = String(format:"%.2x", bytes[13])
            if value == "00"{///唤醒 ,那么让设备进入0x01，设备开机后回进入0x02，之后，正常处理
                self.setupKeyboard("01")
            }else if value == "01"{///正在开机，等待设备进入0x02
                print("开始运行开机logo")
            }else if value == "02"{///正常运行
                guard let p = self.periphral else {return}
                guard let w = self.currentChar else {return}
                guard let d = self.currentData else {return}
                p.writeValue(d, for: w, type: .withResponse)
                self.setnil()
            }else if value == "03"{///这个是app设定的，断开了蓝牙（或者传输表盘超时）。就会清除这个状态。 所以只有在传输表盘过程中会有这个状态
                print("图片传输状态")
            }else if value == "04"{///息屏，若是app要操作，就要将设备进入0x02
                self.setupKeyboard("02")
            }
        case ("00","02"):///3.2.2固件版本
            let product = bytes[10...11].map{String(format:"%.2x", $0)}.joined()
            let version = bytes[12...14].map{String(format:"%.d", $0)}.joined()
            let version_net = bytes[12...14].map{String(format:"%.2x", $0)}.joined().toDecimal()
            NotificationCenter.default.post(name:BLE322Response, object:["product":product,"version":version,"version_net":"\(version_net)"],userInfo: nil)
            ///端获取定制案参数接口-记事本概要信息
            BleDataTool.share.getNoteInfo()
        case ("09","04"):///3.11.4
            self.setnil()
            let value = String(format:"%.2x", bytes[10])
            NotificationCenter.default.post(name:BLE3114Response, object:value)
        case ("08","04"):///3.10.4
            let value = String(format:"%.2x", bytes[10])
            NotificationCenter.default.post(name:BLE3104Response, object:value)
        case ("08","06"):///3.10.6
            let value = String(format:"%.2x", bytes[10])
            NotificationCenter.default.post(name:BLE3106Response, object:value)
        case ("00","16"):///3.2.21 APP 端获取定制案参数接口-记事本概要信息 回调
            let length = (bytes[3...6].map{String(format:"%.2x", $0)}.joined()).toDecimal()
            let count = (length - 2) / 4
            var i = 0
            var value = [Int]()
            while (i < count){
                let hex = bytes[10+i*4..<10+(i+1)*4].map{String(format:"%.02x", $0)}.joined()
                let  stamp = hex.toDecimal()
                value.append(Int(stamp))
                i += 1
            }
            NotificationCenter.default.post(name:BLE3221Response, object:value)
        case ("03","11"),
            ("03","12"):
            //            let sss = String(format:"commond:%.2x key:%.2x 索引:%.2x 值:%.2x 索引:%.2x 值:%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x", bytes[8],bytes[9],bytes[10],bytes[11],bytes[12],bytes[13],bytes[14],bytes[15],bytes[16],bytes[17],bytes[18],bytes[19],bytes[20])
            //
            //            let text = "\(String(describing: APP.logwindow.input.text!)) \n"
            //            APP.logwindow.input.text = text + sss
            break
        case ("07","02"):///ACK
            let value = String(format:"%.2x", bytes[10])
            let sendCMD = String(format:"%.2x", bytes[11])
            let sendKey = String(format:"%.2x", bytes[12])
            print("ACK : 对应的cmd = \(sendCMD), 对应的key = \(sendKey)")
            if value == "01"{ print("校验后的包，无误")
                switch (sendCMD,sendKey){
                case ("04","01")://3.6.1,设置日期的ack里面，再设置配置3.6.2
                    self.setupConfig()
                case ("04","02"):///3.6.2, APP端设置设备基本信息的ack里面，在获取固件信息(3.2.1)
                    self.firmwareVersion()
                case ("04","0a"):///对应发送日志到键盘的命令，3.6.10，第一次ack是表示日志的标题发送完毕，接着发送日志的内容
                    NotificationCenter.default.post(name:BLE3610Response, object:value)
                case("04","0b"):///删除记事本，3.6.11
                    break
                default:
                    break
                }
            }
            else if value == "02"{ print("校验后的包，有异常，需要APP端重新再发一次包")}
            else if value == "03"{ print("忙碌中，需要APP端稍后重新再发一次包")}
            else if value == "04"{ print("设备不支持当前协议")}
        default:
            break
        }
    }
}

//MARK: - 自定义外围设备模型
/// 自定义外围设备模型
extension BLEDevice{
    @objc class func device(_ peripheral:CBPeripheral)->BLEDevice{
        let model = BLEDevice()
        model.mac = peripheral.mac
        model.name = peripheral.name ?? ""
        model.rssi = peripheral.rssi?.stringValue ?? ""
        model.id = peripheral.identifier.uuidString
        model.stamp = NSDate.currentTimeStamp("yyyy-MM-dd HH:mm:ss")
        model.data = peripheral.advertData as Data
        
        let bytes = [UInt8](peripheral.advertData)
        if bytes.count < 1{
            return model
        }
        model.productNum = String(format:"%02lx", bytes[1]) + String(format:"%02lx", bytes[0])
        return model
    }
}

